/**
 * @file LastWordsManager.js
 * @description 遗言管理模块 - 处理玩家遗言发表
 */

/**
 * 遗言管理器类
 */
export class LastWordsManager {
    constructor(game) {
        this.game = game;
        this.currentLastWords = null; // 当前正在发表遗言的玩家信息
        this.lastWordsContent = {}; // 存储遗言内容 { userId: content }
    }

    /**
     * 开始遗言阶段
     * @param {string} userId - 玩家ID
     * @param {string} reason - 死亡原因 ('vote', 'night', 'shoot', 'poison')
     * @returns {object} 操作结果
     */
    startLastWords(userId, reason) {
        const player = this.game.players.find(p => p.userId === userId);
        if (!player) {
            return { success: false, message: '玩家不存在。' };
        }

        // 只有白天被投票放逐的玩家才有遗言
        if (reason !== 'vote') {
            return { success: false, shouldSkip: true };
        }

        // 白痴翻牌后没有遗言
        if (player.tags && player.tags.includes('REVEALED_IDIOT')) {
            return { success: false, shouldSkip: true };
        }

        this.currentLastWords = {
            userId: userId,
            nickname: player.nickname,
            tempId: player.tempId,
            role: player.role,
            startTime: Date.now(),
            duration: 45 * 1000, // 45秒遗言时间
            reason: reason
        };

        return {
            success: true,
            message: `${player.nickname}(${player.tempId}号) 被放逐，现在有45秒时间发表遗言。\n请直接在群内发送遗言内容。`,
            player: player
        };
    }

    /**
     * 记录遗言内容
     * @param {string} userId - 玩家ID
     * @param {string} content - 遗言内容
     * @returns {object} 操作结果
     */
    recordLastWords(userId, content) {
        if (!this.currentLastWords || this.currentLastWords.userId !== userId) {
            return { success: false, message: '当前不是你的遗言时间。' };
        }

        // 检查是否超时
        const elapsed = Date.now() - this.currentLastWords.startTime;
        if (elapsed > this.currentLastWords.duration) {
            return { success: false, message: '遗言时间已结束。' };
        }

        this.lastWordsContent[userId] = content;
        return {
            success: true,
            message: '遗言已记录。'
        };
    }

    /**
     * 结束遗言阶段
     * @returns {object} 结果
     */
    endLastWords() {
        if (!this.currentLastWords) {
            return { success: false, message: '当前没有进行中的遗言阶段。' };
        }

        const userId = this.currentLastWords.userId;
        const player = this.game.players.find(p => p.userId === userId);
        const content = this.lastWordsContent[userId];

        const result = {
            success: true,
            player: player,
            hasLastWords: !!content,
            content: content || null,
            summary: content 
                ? `${player.nickname}(${player.tempId}号) 的遗言："${content}"` 
                : `${player.nickname}(${player.tempId}号) 没有发表遗言。`
        };

        // 记录到事件日志
        this.game.gameState.eventLog.push({
            day: this.game.gameState.currentDay,
            phase: 'day',
            type: 'LAST_WORDS',
            actor: this.game.getPlayerInfo(userId),
            content: content || '(无遗言)'
        });

        // 清空当前遗言状态
        this.currentLastWords = null;

        return result;
    }

    /**
     * 获取当前遗言状态
     */
    getCurrentStatus() {
        if (!this.currentLastWords) return null;

        const elapsed = Date.now() - this.currentLastWords.startTime;
        const remaining = Math.max(0, this.currentLastWords.duration - elapsed);

        return {
            userId: this.currentLastWords.userId,
            nickname: this.currentLastWords.nickname,
            tempId: this.currentLastWords.tempId,
            remainingTime: Math.floor(remaining / 1000),
            hasContent: !!this.lastWordsContent[this.currentLastWords.userId]
        };
    }

    /**
     * 检查是否在遗言阶段
     */
    isInLastWordsPhase() {
        return this.currentLastWords !== null;
    }

    /**
     * 检查是否是当前发言者
     */
    isCurrentSpeaker(userId) {
        return this.currentLastWords && this.currentLastWords.userId === userId;
    }

    /**
     * 序列化为JSON（用于保存游戏状态）
     */
    toJSON() {
        return {
            currentLastWords: this.currentLastWords,
            lastWordsContent: this.lastWordsContent
        };
    }

    /**
     * 从JSON恢复（用于加载游戏状态）
     */
    static fromJSON(game, data) {
        const manager = new LastWordsManager(game);
        if (data) {
            manager.currentLastWords = data.currentLastWords || null;
            manager.lastWordsContent = data.lastWordsContent || {};
        }
        return manager;
    }
}

